package com.learn.core.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.learn.common.annotation.Log;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.utils.Crowns;
import com.learn.common.utils.DateUtils;
import com.learn.common.utils.OSSUploadUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.file.FileUtils;
import com.learn.framework.enums.ErrorCodeEnum;
import com.learn.framework.utils.ApiAssert;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 通用请求处理
 *
 * @author Crown
 */
@Api("用户")
@RestController
@RequestMapping("/common")
@CrossOrigin
public class CommonController extends WebController {

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     */
    @GetMapping("/download")
    @ResponseBody
    public void fileDownload(String fileName) {
        try {
            ApiAssert.isTrue(ErrorCodeEnum.FILE_ILLEGAL_FILENAME.overrideMsg(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName)), FileUtils.isValidFilename(fileName));
            String realFileName = fileName + "_" + DateUtils.dateTimeNow() + ".xls" ;
            String filePath = Crowns.getDownloadPath(fileName+".xls");
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            ApiAssert.failure(ErrorCodeEnum.FILE_DOWNLOAD_FAIL);
        }
    }

    /**
     * 视频上传请求
     */
    @ApiOperation(value = "视频上传请求")
    @PostMapping("/upload")
    @ResponseBody
    @Log(title = "上传文件", businessType = BusinessType.OTHER, operatorType = OperatorType.SYSTEM)
    public JSONObject uploadFile(@RequestParam("file") MultipartFile file) {
        JSONObject json = new JSONObject();
        String filename = file.getOriginalFilename();
        String randomFileName = randomFileName();
        String url;
        try {
            String suffix = filename.substring(filename.lastIndexOf("."));
            if (suffix.toLowerCase().equals(".avi") || suffix.toLowerCase().equals(".mov") || suffix.toLowerCase().equals(".rmvb")
                    || suffix.toLowerCase().equals(".rm") || suffix.toLowerCase().equals(".flv") || suffix.toLowerCase().equals(".mp4")) {
                url = OSSUploadUtil.uploadFile(multipartFileToFile(file), suffix.toLowerCase(), "learn/upload/" + randomFileName + suffix);
            } else {
                json.put("flag", false);
                json.put("code", "0");
                json.put("url", "上传格式不正确,允许上传的文件格式有：avi|mov|rmvb|rm|flv|mp4!");
                return json;
            }
            if (file == null) {
                json.put("code", "0");
                json.put("flag", false);
                json.put("url", "要上传的文件不存在!");
                return json;
            } else {
                json.put("flag", true);
                json.put("code", "1");
                json.put("fileName", filename);
                json.put("url", "https://zhongfujiazheng." + url);
                return json;
            }
        } catch (Exception e) {
            json.put("flag", false);
            json.put("code", "0");
            json.put("url", "上传失败,请联系管理员!");
            return json;
        }
    }

    /**
     * 视频上传请求
     */
    @ApiOperation(value = "比赛视频上传请求")
    @PostMapping("/uploadMatch")
    @ResponseBody
    @Log(title = "比赛视频上传", businessType = BusinessType.OTHER, operatorType = OperatorType.SYSTEM)
    public JSONObject uploadMatchFile(@RequestParam("file") MultipartFile file) {
        JSONObject json = new JSONObject();
        String filename = file.getOriginalFilename();
        String randomFileName = randomFileName();
        String url;
        try {
            String suffix = filename.substring(filename.lastIndexOf("."));
            if (suffix.toLowerCase().equals(".avi") || suffix.toLowerCase().equals(".mov") || suffix.toLowerCase().equals(".rmvb")
                    || suffix.toLowerCase().equals(".rm") || suffix.toLowerCase().equals(".flv") || suffix.toLowerCase().equals(".mp4")) {
                url = OSSUploadUtil.uploadFile(multipartFileToFile(file), suffix.toLowerCase(), "learn/match/" + randomFileName + suffix);
            } else {
                json.put("flag", false);
                json.put("code", "0");
                json.put("url", "上传格式不正确,允许上传的文件格式有：avi|mov|rmvb|rm|flv|mp4!");
                return json;
            }
            if (file == null) {
                json.put("code", "0");
                json.put("flag", false);
                json.put("url", "要上传的文件不存在!");
                return json;
            } else {
                json.put("flag", true);
                json.put("code", "1");
                json.put("fileName", filename);
                json.put("url", "https://zhongfujiazheng." + url);
                return json;
            }
        } catch (Exception e) {
            json.put("flag", false);
            json.put("code", "0");
            json.put("url", "上传失败,请联系管理员!");
            return json;
        }
    }

    /**
     * 头像上传请求
     */
    @ApiOperation(value = "头像上传请求")
    @PostMapping("/uploadAvatar")
    @ResponseBody
    @Log(title = "上传文件", businessType = BusinessType.OTHER, operatorType = OperatorType.SYSTEM)
    public JSONObject uploadAvatar(@RequestParam("file") MultipartFile file) {
        JSONObject json = new JSONObject();
        String filename = file.getOriginalFilename();
        String randomFileName = randomFileName();
        String url;
        try {
            String suffix = filename.substring(filename.lastIndexOf("."));
            if (suffix.toLowerCase().equals(".jpg") || suffix.toLowerCase().equals(".jpeg") || suffix.toLowerCase().equals(".png") || suffix.toLowerCase().equals(".bmp")) {
                url = OSSUploadUtil.uploadFile(multipartFileToFile(file), suffix.toLowerCase(), "learn/avatar/" + randomFileName + suffix);
            } else {
                json.put("flag", false);
                json.put("code", "0");
                json.put("url", "上传文件格式不正确,允许上传的文件格式有：jpg|png|bmp!");
                return json;
            }
            if (file == null) {
                json.put("flag", false);
                json.put("code", "0");
                json.put("url", "要上传的文件不存在!");
                return json;
            } else {
                json.put("flag", true);
                json.put("code", "1");
                json.put("fileName", filename);
                json.put("url", "https://zhongfujiazheng." + url);
                return json;
            }
        } catch (Exception e) {
            json.put("flag", false);
            json.put("url", "文件失败,请联系管理员!");
            return json;
        }
    }

    /**
     * 封面上传请求
     */
    @ApiOperation(value = "封面上传请求")
    @PostMapping("/uploadCover")
    @ResponseBody
    @Log(title = "上传文件", businessType = BusinessType.OTHER, operatorType = OperatorType.SYSTEM)
    public JSONObject uploadCover(@RequestParam("file") MultipartFile file) {
        JSONObject json = new JSONObject();
        String filename = file.getOriginalFilename();
        String randomFileName = randomFileName();
        String url;
        try {
            String suffix = filename.substring(filename.lastIndexOf("."));
            if (suffix.toLowerCase().equals(".jpg") || suffix.toLowerCase().equals(".jpeg") || suffix.toLowerCase().equals(".png") || suffix.toLowerCase().equals(".bmp")) {
                url = OSSUploadUtil.uploadFile(multipartFileToFile(file), suffix.toLowerCase(), "learn/cover/" + randomFileName + suffix);
            } else {
                json.put("flag", false);
                json.put("code", "0");
                json.put("url", "上传文件格式不正确,允许上传的文件格式有：jpg|png|bmp!");
                return json;
            }
            if (file == null) {
                json.put("flag", false);
                json.put("code", "0");
                json.put("url", "要上传的文件不存在!");
                return json;
            } else {
                json.put("flag", true);
                json.put("code", "1");
                json.put("fileName", filename);
                json.put("url", "https://zhongfujiazheng." + url);
                return json;
            }
        } catch (Exception e) {
            json.put("flag", false);
            json.put("url", "文件失败,请联系管理员!");
            return json;
        }
    }

    public static String randomFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = simpleDateFormat.format(date);
        return fileName;
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
